<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\shop_admin\middleware;

use app\shop_admin\model\Merchant;
use think\facade\Cache;
use think\facade\Db;
use think\helper\Str;
use think\Response;

class CheckToken
{
    /**
     * 全局处理token
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function handle($request, \Closure $next)
    {
        global $token, $uri, $user;
        $token = request()->header('Authorization') ?? input('get.Authorization');
        $dischargedArr = ['operation/login', 'operation/logout'];

        $uri = Str::lower(request()->pathinfo());

        if ($uri === 'operation/logout' || $uri == "dada_call_back") {
            return $next($request);
        }

        if (!$token) {
            if (in_array($uri, $dischargedArr)) {
                return $next($request);
            }

            return \json(['msg' => '请登录'])->code(HTTP_UNAUTH);
        }

        $ip = getIp();

        if ($uri === 'operation/login') {

            if (strpos($token, "shop_") !== false) { //shop端登录
                $user = Cache::store('redis')->get("shop_token:" . $token);
                if ($user && $user->login_ip === $ip) {

                    $typeIndate = Db::table('jiecheng_lessee')
                        ->where(['status' =>1])
                        ->whereNull("delete_time")
                        ->field('type,indate,site')
                        ->find($user->mall_id);
                    if (!$typeIndate){
                        return \json(['msg' => '商城已禁用'])->code(HTTP_UNAUTH);
                    }
                    if ($typeIndate['type'] === 0 && (empty($typeIndate['indate']) || strtotime($typeIndate['indate']) < time())){
                        return \json(['msg' => '商城已过期，请联系管理员续费'])->code(HTTP_UNAUTH);
                    }

                    return \json(['msg' => '已登录'])->code(HTTP_SUCCESS)->header(['shop_token' => $token]);
                }
            } elseif (strpos($token, "mall_") !== false) { //mall登录
                $user = Cache::store('redis')->get("mall_token:" . $token);
                if (!$user) {
                    return \json(['msg' => '请登录'])->code(HTTP_UNAUTH);
                }

                if ($user->login_ip !== $ip) {
                    Cache::store('redis')->delete("mall_token:" . $token);
                    return \json(['msg' => '请先登录'])->code(HTTP_UNAUTH);
                }
                $merchantId = request()->post("merchant_id");
                if (empty($merchantId)) {
                    return \json(['msg' => '请使用正确的登录方式'])->code(HTTP_UNAUTH);
                }
                $merchant = Merchant::find($merchantId);
                if (!$merchant) {
                    return \json(['msg' => '商户不存在'])->code(HTTP_UNAUTH);
                }

                $user->merchant_merchant_id = $user->merchant_id;
                $user->shop_merchant_id = $merchantId;
                $user->used_affiliation = 'shop';

                $user->merchant_id = $merchantId;
                Cache::store('redis')->set("mall_token:" . $token, $user, 60 * 60 * 24 * 30);

                $msg = [
                    "user" => $user->username,
                    "site" => $merchant->name,
                ];

                $typeIndate = Db::table('jiecheng_lessee')
                    ->where(['status' =>1])
                    ->whereNull("delete_time")
                    ->field('type,indate,site')
                    ->find($user->mall_id);
                if (!$typeIndate){
                    return \json(['msg' => '商城已禁用'])->code(HTTP_UNAUTH);
                }
                if ($typeIndate['type'] === 0 && (empty($typeIndate['indate']) || strtotime($typeIndate['indate']) < time())){
                    return \json(['msg' => '商城已过期，请联系管理员续费'])->code(HTTP_UNAUTH);
                }

                return \json(['msg' => $msg])->code(HTTP_SUCCESS);

            } elseif (strpos($token, "saas_") !== false) { //saas登录
                $user = Cache::store('redis')->get("saas_token:" . $token);
                if (!$user) {
                    return \json(['msg' => '请登录'])->code(HTTP_UNAUTH);
                }
                if ($user->login_ip !== $ip) {
                    Cache::store('redis')->delete("saas_token:" . $token);
                    return \json(['msg' => '请先登录'])->code(HTTP_UNAUTH);
                }
                if (!isset($user->mall_id) || empty($user->mall_id)) {
                    return \json(['msg' => '请使用正确的登录方式'])->code(HTTP_UNAUTH);
                }
                $merchantId = request()->post("merchant_id");
                if (empty($merchantId)) {
                    return \json(['msg' => '请使用正确的登录方式'])->code(HTTP_UNAUTH);
                }
                $merchant = Merchant::find($merchantId);
                if (!$merchant) {
                    return \json(['msg' => '商户不存在'])->code(HTTP_UNAUTH);
                }

                $user->merchant_merchant_id = $user->merchant_id;
                $user->shop_merchant_id = $merchantId;
                $user->used_affiliation = 'shop';

                $user->merchant_id = $merchantId;
                Cache::store('redis')->set("saas_token:" . $token, $user, 60 * 60 * 24 * 30);

                $msg = [
                    "user" => $user->username,
                    "site" => $merchant->name,
                ];

                $typeIndate = Db::table('jiecheng_lessee')
                    ->where(['status' =>1])
                    ->whereNull("delete_time")
                    ->field('type,indate,site')
                    ->find($user->mall_id);
                if (!$typeIndate){
                    return \json(['msg' => '商城已禁用'])->code(HTTP_UNAUTH);
                }
                if ($typeIndate['type'] === 0 && (empty($typeIndate['indate']) || strtotime($typeIndate['indate']) < time())){
                    return \json(['msg' => '商城已过期，请联系管理员续费'])->code(HTTP_UNAUTH);
                }

                return \json(['msg' => $msg])->code(HTTP_SUCCESS);

            } elseif (strpos($token, "suser_") !== false) { //suser登录
                $user = Cache::store('redis')->get("suser_token:" . $token);
                if (!$user) {
                    return \json(['msg' => '请登录'])->code(HTTP_UNAUTH);
                }
                if ($user->login_ip !== $ip) {
                    Cache::store('redis')->delete("suser_token:" . $token);
                    return \json(['msg' => '请先登录'])->code(HTTP_UNAUTH);
                }
                if (!isset($user->mall_id) || empty($user->mall_id)) {
                    return \json(['msg' => '请使用正确的登录方式'])->code(HTTP_UNAUTH);
                }
                $merchantId = request()->post("merchant_id");
                if (empty($merchantId)) {
                    return \json(['msg' => '请使用正确的登录方式'])->code(HTTP_UNAUTH);
                }
                $merchant = Merchant::find($merchantId);
                if (!$merchant) {
                    return \json(['msg' => '商户不存在'])->code(HTTP_UNAUTH);
                }

                $user->merchant_merchant_id = $user->merchant_id;
                $user->shop_merchant_id = $merchantId;
                $user->used_affiliation = 'shop';

                $user->merchant_id = $merchantId;
                Cache::store('redis')->set("suser_token:" . $token, $user, 60 * 60 * 24 * 30);

                $msg = [
                    "user" => $user->username,
                    "site" => $merchant->name,
                ];

                $typeIndate = Db::table('jiecheng_lessee')
                    ->where(['status' =>1])
                    ->whereNull("delete_time")
                    ->field('type,indate,site')
                    ->find($user->mall_id);
                if (!$typeIndate){
                    return \json(['msg' => '商城已禁用'])->code(HTTP_UNAUTH);
                }
                if ($typeIndate['type'] === 0 && (empty($typeIndate['indate']) || strtotime($typeIndate['indate']) < time())){
                    return \json(['msg' => '商城已过期，请联系管理员续费'])->code(HTTP_UNAUTH);
                }

                return \json(['msg' => $msg])->code(HTTP_SUCCESS);
            }

        } else {
            if (strpos($token, "shop_") !== false) { //shop
                $user = Cache::store('redis')->get("shop_token:" . $token);
                if (!$user) {
                    Cache::store('redis')->delete("shop_token:" . $token);
                    return \json(['msg' => '请登录'])->code(HTTP_UNAUTH);
                }

                if ($user->login_ip !== $ip) {
                    Cache::store('redis')->delete("shop_token:" . $token);
                    return \json(['msg' => '请先登录'])->code(HTTP_UNAUTH);
                }
            } elseif (strpos($token, "mall_") !== false) { //mall
                $user = Cache::store('redis')->get("mall_token:" . $token);
                if (!$user) {
                    Cache::store('redis')->delete("mall_token:" . $token);
                    return \json(['msg' => '请登录'])->code(HTTP_UNAUTH);
                }

                if ($user->login_ip !== $ip) {
                    Cache::store('redis')->delete("mall_token:" . $token);
                    return \json(['msg' => '请先登录'])->code(HTTP_UNAUTH);
                }
                if (
                    !isset($user->mall_id, $user->merchant_id) ||
                    empty($user->mall_id) ||
                    empty($user->merchant_id)
                ) {
                    return \json(['msg' => '请使用正确的登录方式'])->code(HTTP_UNAUTH);
                }

            } elseif (strpos($token, "saas_") !== false) { //saas

                $user = Cache::store('redis')->get("saas_token:" . $token);
                if (!$user) {
                    return \json(['msg' => '请登录'])->code(HTTP_UNAUTH);
                }

                if ($user->login_ip !== $ip) {
                    Cache::store('redis')->delete("saas_token:" . $token);
                    return \json(['msg' => '请先登录'])->code(HTTP_UNAUTH);
                }
                if (
                    !isset($user->mall_id, $user->merchant_id) ||
                    empty($user->mall_id) ||
                    empty($user->merchant_id)
                ) {
                    return \json(['msg' => '请使用正确的登录方式'])->code(HTTP_UNAUTH);
                }

            } elseif (strpos($token, "suser_") !== false) { //suser
                $user = Cache::store('redis')->get("suser_token:" . $token);
                if (!$user) {
                    return \json(['msg' => '请登录'])->code(HTTP_UNAUTH);
                }

                if ($user->login_ip !== $ip) {
                    Cache::store('redis')->delete("suser_token:" . $token);
                    return \json(['msg' => '请先登录'])->code(HTTP_UNAUTH);
                }
                if (
                    !isset($user->mall_id, $user->merchant_id) ||
                    empty($user->mall_id) ||
                    empty($user->merchant_id)
                ) {
                    return \json(['msg' => '请使用正确的登录方式'])->code(HTTP_UNAUTH);
                }

            } else {
                return \json(['msg' => '请使用正确的登录方式'])->code(HTTP_UNAUTH);
            }

            if (strpos($token, "shop_") !== false) {
                return $next($request);
            }

            $loginAffiliation = request()->header('Affiliation');

            if ('shop' === $loginAffiliation) {
                if ('mall' === $user->used_affiliation) {
                    $user->merchant_id = $user->shop_merchant_id;
                    $user->used_affiliation = 'shop';
                    if (strpos($token, "mall_") !== false) { //mall登录
                        Cache::store('redis')->set("mall_token:" . $token, $user, 60 * 60 * 24 * 30);
                    } elseif (strpos($token, "saas_") !== false) { //saas登录
                        Cache::store('redis')->set("saas_token:" . $token, $user, 60 * 60 * 24 * 30);
                    } elseif (strpos($token, "suser_") !== false) { //suser登录
                        Cache::store('redis')->set("saas_token:" . $token, $user, 60 * 60 * 24 * 30);
                    }
                }

            } elseif ('mall' === $loginAffiliation) {
                if ('shop' === $user->used_affiliation) {
                    $user->merchant_id = $user->merchant_merchant_id;
                    $user->used_affiliation = 'mall';
                    if (strpos($token, "mall_") !== false) { //mall登录
                        Cache::store('redis')->set("mall_token:" . $token, $user, 60 * 60 * 24 * 30);
                    } elseif (strpos($token, "saas_") !== false) { //saas登录
                        Cache::store('redis')->set("saas_token:" . $token, $user, 60 * 60 * 24 * 30);
                    } elseif (strpos($token, "suser_") !== false) { //suser登录
                        Cache::store('redis')->set("saas_token:" . $token, $user, 60 * 60 * 24 * 30);
                    }
                }
            }

//            $typeIndate = Db::table('jiecheng_lessee')
//                ->where(['status' =>1])
//                ->whereNull("delete_time")
//                ->field('type,indate,site')
//                ->find($user->mall_id);
//            if (!$typeIndate){
//                return \json(['msg' => '商城已禁用'])->code(HTTP_UNAUTH);
//            }
//            if ($typeIndate['type'] === 0 && (empty($typeIndate['indate']) || strtotime($typeIndate['indate']) < time())){
//                return \json(['msg' => '商城已过期，请联系管理员续费'])->code(HTTP_UNAUTH);
//            }
        }
        $open_url = ["pic/geturl"];
        if (empty(request()->header("pageaction")) && !in_array($uri, $open_url) && strpos($token, "mall_")) {
            return \json(['msg' => '无权限！'])->code(HTTP_FORBIDDEN);
        }
        return $next($request);
    }
}
